<template>
  <ContentField>
    <div class="row justify-content-md-center">
      <div class="col-3">
        <form @submit.prevent="login">
          <div class="mb-3">
            <label for="username" class="form-label">用户名</label>
            <input type="text" v-model="username" class="form-control" id="username" >
          </div>
          <div class="mb-3">
            <label for="password" class="form-label">密码</label>
            <input type="password" v-model="password"  class="form-control" id="password">
          </div>
          <div class="error_message">{{ error_message }}</div>
          <button type="submit" class="btn btn-primary">登录</button>
        </form>
      </div> 
    </div>
    
  </ContentField>
</template>

<script>
import ContentField from '../components/ContentField.vue';
import { ref } from 'vue';
import { useStore } from 'vuex';
import router from '../router/index';

export default {
    name: 'LoginView',
    components: {
        ContentField,
    },
    setup() {
        const store = useStore();
        let username = ref('');
        let password = ref('');
        let error_message = ref('');

        const myspace_token = localStorage.getItem('myspace_token');
        if(myspace_token) {
          store.commit('updateToken', myspace_token);
          store.dispatch('getinfo', {
            success() {
              router.push({name: 'userlist'});
            }
          })
        }

        const login = () => {
            store.dispatch('login', {
              username: username.value,
              password: password.value,
              success() {//执行getinfo函数
                store.dispatch('getinfo', {
                  success() {
                    router.push({name: 'userlist'});//登录成功后跳转到用户列表页面
                  },
                });
              },
              error() {
                error_message.value = '用户名或者密码错误!';
              }
            });
        };

        return {
            username,
            password,
            login,
            error_message,
        }
    },
}
</script>

<style scoped>
button {
    width: 100%;
}

.error_message {
  color: red;
}
</style>